package com.jsm.tf.controller;

import com.google.common.collect.Lists;
import com.jsm.tf.director.Director;
import com.jsm.tf.net.NettyClient;
import com.jsm.tf.net.message.request.JoinRoomMessage;
import com.jsm.tf.net.message.response.JoinRoomResponseMessage;
import com.jsm.tf.room.RoomDTO;
import com.jsm.tf.service.RoomService;
import com.jsm.tf.view.RoomView;
import com.jsm.tf.view.dialog.TFDialog;
import com.jsm.tf.vo.RoomListVO;
import de.felixroske.jfxsupport.FXMLController;
import de.felixroske.jfxsupport.GUIState;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.util.Pair;

import javax.annotation.Resource;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;


@FXMLController
public class RoomListController implements Initializable {

    @FXML
    private TableColumn<RoomListVO, String> creatorName;

    @FXML
    private TableColumn<RoomListVO, Long> id;

    @FXML
    private TableView<RoomListVO> roomList;

    @FXML
    private TableColumn<RoomListVO, String> roomName;
    @FXML
    private TableColumn<RoomListVO, String> operator;

    @Resource
    private RoomService roomService;
    @Resource
    private Director director;
    @Resource
    private NettyClient nettyClient;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        List<RoomDTO> rooms = roomService.listRoom(director.nextPage(), director.getPageSize());
        addRooms(rooms);
    }

    private void addRooms(List<RoomDTO> rooms) {
        if (rooms == null) {
            return;
        }
        List<RoomListVO> roomListVOs = Lists.newArrayList();
        for (RoomDTO room : rooms) {
            RoomListVO roomListVO = new RoomListVO();
            roomListVO.setRoomName(room.getName());
            roomListVO.setCreatorId(room.getCreatorId());
            roomListVO.setCreatorNickname(room.getCreatorNickName());
            roomListVO.setId(room.getId());
            ButtonBar buttonBar = new ButtonBar();
            Button joinButton = new Button("加入房间");
            joinButton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    JoinRoomMessage joinRoomMessage = new JoinRoomMessage();
                    joinRoomMessage.setRoomId(room.getId());
                    JoinRoomResponseMessage response = nettyClient.sendSyncMsg(joinRoomMessage);
                    if (response != null && response.isSuccess()) {
                        director.setRoom(response.getRoom());
                        director.showView(RoomView.class);
                    }
                }
            });

            Button roomInfoButton = new Button("房间信息");
            roomInfoButton.setOnAction(event -> System.out.println(" roomInfo"));

            buttonBar.getButtons().add(joinButton);
            buttonBar.getButtons().add(roomInfoButton);
            roomListVO.setButtonBar(buttonBar);
            roomListVOs.add(roomListVO);
        }
        final ObservableList<RoomListVO> data = FXCollections.observableArrayList(roomListVOs);
        id.setCellValueFactory(new PropertyValueFactory<>("id"));
        roomName.setCellValueFactory(new PropertyValueFactory<>("roomName"));
        creatorName.setCellValueFactory(new PropertyValueFactory<>("creatorNickname"));
        operator.setCellValueFactory(new PropertyValueFactory<>("buttonBar"));
        roomList.setItems(data);
    }

    public void reflush() {
        addRooms(roomService.listRoom(director.nextPage(), director.getPageSize()));
    }

    public void createRoom(MouseEvent mouseEvent) {
        Dialog<Pair<String, String>> dialog = new Dialog<Pair<String, String>>();
        dialog.setTitle("创建房间");
        dialog.setHeaderText("请输入房间名称");
        ButtonType loginButtonType = new ButtonType("创建", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField roomName = new TextField();
        roomName.setPromptText("房间名称");

        grid.add(new Label("房间名称:"), 0, 0);
        grid.add(roomName, 1, 0);
        dialog.getDialogPane().setContent(grid);
        Node createButton = dialog.getDialogPane().lookupButton(loginButtonType);
        createButton.setDisable(true);

        roomName.textProperty().addListener((observable, oldValue, newValue) -> {
            createButton.setDisable(newValue.trim().isEmpty());
        });

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == loginButtonType) {
                return new Pair<>("roomName", roomName.getText());
            }
            return null;
        });

        Optional<Pair<String, String>> result = dialog.showAndWait();

        result.ifPresent(pair -> {
            String name = pair.getValue();
            roomService.createRoom(name);
        });
    }
    public void previousPage(MouseEvent mouseEvent) {
        int page = director.getPage();
        if (page <= 1) {
            TFDialog.showMessageDialog(GUIState.getStage(), "没有上一页了", "提示");
        }
        roomService.listRoom(director.previousPage(), director.getPageSize());
    }

    public void nextPage(MouseEvent mouseEvent) {

    }
}
